package com.gofun.framework.dubbo.core.environment;

import org.springframework.core.env.Environment;

import com.alibaba.dubbo.common.utils.StringUtils;

/**
 * @Project       : framework-dubbo-core
 * @Program Name  : com.ljt.framework.dubbo.core.environment.DefaultResolveMapping.java
 * @Description   : 解决环境变量和系统属性的映射问题
 * @Author        : wangchao
 * @Creation Date : 2016年5月29日 下午6:26:28 
 */
public class DefaultResolveStrategy {
	
	
	public enum ResolveStrategyEnum{
		
		DIRECT("直接配置",new AbstractResolveStrategy () {
			@Override
			public void parse(Environment env, ConfigMapping mapping) {
				String value = env.getProperty(mapping.getCode());
        		if(StringUtils.isEmpty(value) || !isActivated(env, mapping))
        			return ;
        		logger.info("valid properties :" + mapping.getCode() + "=" + value);
				System.setProperty(mapping.getCode(),env.getProperty(mapping.getCode()));
			}
		}),
		
		P2P("解析点对点直连服务提供者的配置",new AbstractResolveStrategy(){

			@Override
			public void parse(Environment env, ConfigMapping mapping) {
				if(!isActivated(env, mapping))
					return;
				logger.info("development environment for the use of direct service");
				int index = 0;
				String property = env.getProperty(getKey(index));
				while (StringUtils.isNotEmpty(property)) {
					logger.info("reference:" + index + "," + property);
					String[] tmp = property.split("=");
					if(tmp == null || tmp.length < 2)
						continue;
					System.setProperty(tmp[0], tmp[1]);
					index++;
					property = env.getProperty(getKey(index));
				}
			}
			
			private String getKey(int index){
				return "reference[" + index + "]";
			}
			
		})
		
		;
		
		public ResolveMappingStrategy resolve;
		
		public String desc;
		
		private ResolveStrategyEnum(String desc,ResolveMappingStrategy resolve) {
			this.desc = desc;
			this.resolve = resolve;
		}
	}
	
}
